close all;
clear;
clc;
data = load('ex1data2.txt'); 	%1st cloumn is house size(in square feet),2nd's is bedrooms number,3th is house price
x = data(:,1:2);
y = data(:,3);
len = length(y);
mu = mean(x);			%取房子的面积和房间的平局值
sigma = std(x);			%取房子的面积和房间的标准差
x = (x - repmat(mu,size(x,1),1)) ./ repmat(sigma,size(x,1),1);
				%进行标准缩放

alpha = 0.01;			%设置学习率
iter_numbers = 8000;		%设置迭代次数
theta = zeros(3,1);		%初始化参数
cost_value = zeros(iter_numbers,1);
x = [ones(len,1),x];		%增加一行的目的是为了能够进行矩阵相乘，能够这样做的理由是1乘任何数还等于任何数，对计算结果不产生影响
for i = 1:iter_numbers
	theta = theta - alpha / len * x' * (x * theta - y);
				%矩阵乘法规则：行x列对应相乘再相加，与sum求和函数功能一样
	cost_value(i) = sum((x * theta - y) .^2) / (2 * len);
end
figure;
plot(1:numel(cost_value),cost_value,'r*');

theta1 = pinv(x' * x) * x' *y;	%正规方程法求使代价函数最小的参数theta1

